package com.rjpacket.supernews.app;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.BoringLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import android.view.*;
import android.widget.*;
import com.rjpacket.supernews.app.adapters.SlidingPaneMenuGridAdapter;
import com.rjpacket.supernews.app.adapters.SlidingPaneMenuListAdapter;
import com.rjpacket.supernews.app.adapters.ViewPagerCommonAdapter;
import com.rjpacket.supernews.app.databases.DBHelper;
import com.rjpacket.supernews.app.fragments.DuanziFragment;
import com.rjpacket.supernews.app.fragments.FunnyFragment;
import com.rjpacket.supernews.app.fragments.ImageFragment;
import com.rjpacket.supernews.app.fragments.RecommendFragment;
import com.rjpacket.supernews.app.models.CategoryTitle;
import com.rjpacket.supernews.app.myviews.MyHeadView;
import com.rjpacket.supernews.app.utils.DataContainer;
import com.rjpacket.supernews.app.utils.MyImageLoadMethod;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

//主界面，实现ViewPager联动以及侧滑
public class MainActivity extends FragmentActivity implements AdapterView.OnItemClickListener, View.OnClickListener, ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener {

    private DataContainer dc;
    private RadioGroup radioGroup;
    private ViewPager pager;
    private LinkedList<Fragment> fragments;

    private boolean tag = true;
    private View view;

    private long lastTime;
    private int screenHalf;
    private HorizontalScrollView scrollView;
    private boolean isLogin;
    private TextView textView;
    private ImageView imageView1;
    private ImageView mainHead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sp = getSharedPreferences(Constants.SP_APP, MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putBoolean(Constants.SP_KEY_TUTORIAL_SHOW, false);
        edit.commit();

        dc = DataContainer.getInstance();

        scrollView = (HorizontalScrollView) findViewById(R.id.horizontalscrollview);
        scrollView.setHorizontalScrollBarEnabled(false);

        view = findViewById(R.id.main);

        //TODO 实现radioGroup
        radioGroup = (RadioGroup) findViewById(R.id.category_radio_group);
        pager = (ViewPager) findViewById(R.id.viewpager_main);

        Display d = getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        d.getMetrics(dm);
        screenHalf = d.getWidth() / 2;

        fragments = new LinkedList<Fragment>();
        initRadioGroup();

        //设置侧滑菜单选项
        SlidingMenu slidingMenu = new SlidingMenu(this, SlidingMenu.SLIDING_CONTENT);
        //设置一个菜单
        slidingMenu.setMenu(R.layout.menu);
        //菜单支持左滑
        slidingMenu.setMode(SlidingMenu.LEFT);
        //内容保留区宽度
        slidingMenu.setBehindOffset(200);
        //设置滑出菜单区域
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        slidingMenu.setTouchmodeMarginThreshold(100);
        //设置侧滑菜单显示内容
        ListView listView = (ListView) findViewById(R.id.sj_main_listView);
        GridView gridView = (GridView) findViewById(R.id.sj_main_gridView);

        textView = (TextView) findViewById(R.id.text);

        imageView1 = (ImageView) findViewById(R.id.main_menu_login);
        imageView1.setOnClickListener(this);

        mainHead = (ImageView) findViewById(R.id.main_head);
        mainHead.setOnClickListener(this);

        SharedPreferences share = getSharedPreferences(Constants.SP_APP, MODE_PRIVATE);
        isLogin = share.getBoolean("isLogin", false);
        if (isLogin) {
            ShareSDK.initSDK(this);
            Platform plat = new SinaWeibo(this);
            String userName = plat.getDb().getUserName();
            String userIcon = plat.getDb().getUserIcon();
            textView.setText(userName);

            Log.d("userIcon", userIcon);
            MyImageLoadMethod.load(userIcon, imageView1);
            MyImageLoadMethod.load(userIcon, mainHead);
//            Bitmap bitmap = BitmapFactory.decodeByteArray(userIcon.getBytes(), 0, userIcon.getBytes().length);
//            imageView1.setImageBitmap(bitmap);
        }
        //ListView用来显示用户操作的一些信息
        LinkedList<HashMap<String, Object>> list = new LinkedList<HashMap<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("img", R.drawable.menu_left_newssearch);
        map.put("title", "新闻搜索");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.menu_left_mysave);
        map.put("title", "我的收藏");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.menu_left_mymessage);
        map.put("title", "我的消息");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.menu_left_mysetting);
        map.put("title", "我的设置");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("img", R.drawable.menu_left_sendadvice);
        map.put("title", "意见反馈");
        list.add(map);

        SlidingPaneMenuListAdapter adapter = new SlidingPaneMenuListAdapter(this, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);

        //GridView用来显示离线下载以及模式切换
        List<HashMap<String, Object>> data = new LinkedList<HashMap<String, Object>>();
        HashMap<String, Object> map1 = new HashMap<String, Object>();
        map1.put("image", R.drawable.menu_left_download);
        map1.put("titles", "退出登录");
        data.add(map1);

        map1 = new HashMap<String, Object>();
        map1.put("image", R.drawable.menu_left_mode_day);
        map1.put("titles", "夜间模式");
        data.add(map1);

        SlidingPaneMenuGridAdapter adapter1 = new SlidingPaneMenuGridAdapter(this, data);
        gridView.setAdapter(adapter1);
        gridView.setOnItemClickListener(this);


        //pager = (ViewPager) findViewById(R.id.viewpager);


        pager.setAdapter(new ViewPagerCommonAdapter(getSupportFragmentManager(), fragments));
        pager.setOnPageChangeListener(this);

        radioGroup.setOnCheckedChangeListener(this);

        View view = radioGroup.getChildAt(0);
        if (view != null && view instanceof RadioButton) {
            RadioButton rb = (RadioButton) view;
            rb.setChecked(true);
        }

        ImageView imageView = (ImageView) findViewById(R.id.radio_button_select);
        imageView.setOnClickListener(this);

        ImageView loginButton = (ImageView) findViewById(R.id.main_login);
        loginButton.setOnClickListener(this);
    }

    private void initRadioGroup() {
        initDataTitle();
        //每次初始化之前先清空radioGroup

        radioGroup.removeAllViewsInLayout();
        fragments.clear();
//        fragments.add(addFragment("recommend"));

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        dc = DataContainer.getInstance();

        List<CategoryTitle> titles = dc.getCheckedTitles();

        for (CategoryTitle title : titles) {
            if (true) {
                //填加fragment
                switch (title.getId()) {
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                    case 6:
                    case 8:
                    case 9:
                    case 10:
                    case 11:
                    case 12:
                    case 13:
                    case 14:
                    case 16:
                    case 19:
                    case 20:
                    case 21:
                    case 22:
                        fragments.add(addFragment(title.getType()));
                        break;
                    case 3:
                        //TODO 娱乐
//                    fragments.add(new FunnyFragment());
                        fragments.add(addFragment("hotspot"));
                        break;
                    case 7:
                        //TODO 比较特殊,获得本地,131代表北京
                        fragments.add(addFragment("local_131"));
                        break;
                    case 15:
                        //TODO 段子
                        fragments.add(addFragment("hotspot"));
                        break;
                    case 17:
                        //TODO 活动专区
                        fragments.add(addFragment("hotspot"));
                        break;
                    case 18:
                        //TODO 图片
                        //fragments.add(addFragment("hotspot"));
                        fragments.add(new ImageFragment());
                        break;
                }

            }


            //////////////////////////////
            RadioButton rb = new RadioButton(this);

            rb.setWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, metric));

            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
                    RadioGroup.LayoutParams.MATCH_PARENT,
                    RadioGroup.LayoutParams.MATCH_PARENT
            );
            params.setMargins(
                    (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, metric),
                    (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, metric),
                    (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, metric),
                    (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, metric)
            );


            rb.setLayoutParams(params);

            rb.setButtonDrawable(android.R.color.transparent);

            rb.setText(title.getName());

            rb.setGravity(Gravity.CENTER);

            rb.setBackground(getResources().getDrawable(R.drawable.selector_radio_button));

            radioGroup.addView(rb);


        }

        View view = radioGroup.getChildAt(0);
        if (view != null && view instanceof RadioButton) {
            RadioButton rb = (RadioButton) view;
            rb.setChecked(true);
        }

    }

    /**
     * 独家方法，由于个界面相似，用下面方法传递参数创建fragment
     *
     * @param channel
     * @return
     */
    public Fragment addFragment(String channel) {
        RecommendFragment ret = new RecommendFragment();
        Bundle args = new Bundle();
        args.putString("channel", channel);
        ret.setArguments(args);
        return ret;
    }


    @Override
    protected void onDestroy() {
        //TODO 保存相应的设置
        List<CategoryTitle> checkedTitles = dc.getCheckedTitles();
        List<CategoryTitle> unCheckedTitles = dc.getUnCheckedTitles();
        DBHelper dbHelper = new DBHelper(this);
        SQLiteDatabase database = dbHelper.getWritableDatabase();

        database.beginTransaction();
        try {
            for (CategoryTitle title : checkedTitles) {
                ContentValues values = new ContentValues();
                values.put("checked", 1);
                database.update("titles", values, "name = ?", new String[]{title.getName()});
            }

            for (CategoryTitle unTitle : unCheckedTitles) {
                ContentValues values = new ContentValues();
                values.put("checked", 0);
                database.update("titles", values, "name = ?", new String[]{unTitle.getName()});

            }

            database.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            database.endTransaction();
        }
        database.close();

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.radio_button_select:
                Intent intent = new Intent(this, ChannelSelectActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_right_in, R.anim.activity_stop);
                finish();
                break;
            case R.id.main_menu_login:
                if (!isLogin) {
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    startActivityForResult(intent1, 400);
                    overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                }
                break;
            case R.id.main_login:
                if (!isLogin) {
                    Intent intent2 = new Intent(this, LoginActivity.class);
                    startActivityForResult(intent2, 400);
                    overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                } else {
                    Intent intent3 = new Intent(this, UserInfoActivity.class);
                    startActivity(intent3);
                }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //TODO 返回数据的处理
        if (resultCode == 400) {
            SharedPreferences share = getSharedPreferences(Constants.SP_APP, MODE_PRIVATE);
            boolean isLogin1 = share.getBoolean("isLogin", false);
            if (isLogin1) {
                ShareSDK.initSDK(this);
                Platform plat = new SinaWeibo(this);
                String userName = plat.getDb().getUserName();
                String userIcon = plat.getDb().getUserIcon();
                textView.setText(userName);

                Log.d("userIcon", userIcon);
                MyImageLoadMethod.load(userIcon, imageView1);
                MyImageLoadMethod.load(userIcon, mainHead);
//            Bitmap bitmap = BitmapFactory.decodeByteArray(userIcon.getBytes(), 0, userIcon.getBytes().length);
//            imageView1.setImageBitmap(bitmap);
            }
        }

    }

    //菜单里面用户设置和反馈等操作的点击事件
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        switch (adapterView.getId()) {
            case R.id.sj_main_listView:
                switch (i) {
                    case 0:
                        Intent intent = new Intent(this, NewsSearchActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                        break;
                    case 1:
                        Intent intent1 = new Intent(this, MySaveActivity.class);
                        startActivity(intent1);
                        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                        break;
                    case 2:
                        Intent intent2 = new Intent(this, MyMessageActivity.class);
                        startActivity(intent2);
                        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                        break;
                    case 3:
                        Intent intent3 = new Intent(this, MySettingsActivity.class);
                        startActivity(intent3);
                        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                        break;
                    case 4:
                        Intent intent4 = new Intent(this, SendAdviceActivity.class);
                        startActivity(intent4);
                        overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                        break;
                }
                break;
            case R.id.sj_main_gridView:
                switch (i) {
                    case 0:
                        //退出登录
                        ShareSDK.initSDK(this);
                        Platform plat = new SinaWeibo(this);
                        if (plat.isValid()) {
                            plat.removeAccount();
                        }
                        SharedPreferences share = getSharedPreferences(Constants.SP_APP, MODE_PRIVATE);
                        SharedPreferences.Editor editor = share.edit();
                        editor.putBoolean("isLogin", false);
                        editor.commit();
                        finish();
                        break;
                    case 1:
                        if (tag) {
                            this.view.setBackgroundColor(Color.WHITE);
                            tag = false;
                        } else {
                            this.setTheme(R.style.AppTheme);
                            this.view.setBackgroundColor(Color.BLACK);
                            tag = true;
                        }
                        break;
                }
                break;
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        View view = radioGroup.getChildAt(i);
        if (view != null && view instanceof RadioButton) {
            RadioButton rb = (RadioButton) view;
            rb.setChecked(true);
        }

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int count = radioGroup.getChildCount();
        int index = 0;
        for (int i = 0; i < count; i++) {
            View view = radioGroup.getChildAt(i);
            if (view != null && view instanceof RadioButton) {
                RadioButton rb = (RadioButton) view;
                if (rb.isChecked()) {
                    index = i;
                    int scrollX = scrollView.getScrollX();
                    int left = rb.getLeft();
                    int leftScreen = left - scrollX;
                    scrollView.smoothScrollBy((leftScreen - screenHalf), 0);
                    break;
                }
            }
        }
        pager.setCurrentItem(index);

    }

    @Override
    public void onBackPressed() {
        long timeMillis = System.currentTimeMillis();
        if (timeMillis - lastTime < 2000) {

            finish();
        } else {
            lastTime = timeMillis;
            Toast.makeText(this, "再点击一次退出程序...", Toast.LENGTH_SHORT).show();
        }
    }

    public void initDataTitle() {
        //TODO 加载RadioGroup的被选项与非选项
        DataContainer dc = DataContainer.getInstance();
        List<CategoryTitle> checkedTitles = new LinkedList<CategoryTitle>();
        List<CategoryTitle> unCheckedTitles = new LinkedList<CategoryTitle>();

        DBHelper helper = new DBHelper(this);
        SQLiteDatabase database = helper.getWritableDatabase();

        //选中的情况
        Cursor trueCursor = database.query("titles", null, "checked = ?", new String[]{Integer.toString(1)}, null, null, null);
        if (trueCursor != null) {
            while (trueCursor.moveToNext()) {
                CategoryTitle title = new CategoryTitle();
                title.setId(trueCursor.getInt(trueCursor.getColumnIndex("id")));
                title.setName(trueCursor.getString(trueCursor.getColumnIndex("name")));
                int checked = trueCursor.getInt(trueCursor.getColumnIndex("checked"));
                if (checked == 1) {
                    title.setChecked(true);
                } else {
                    title.setChecked(false);
                }
                title.setType(trueCursor.getString(trueCursor.getColumnIndex("type")));

                checkedTitles.add(title);
            }
            trueCursor.close();
        }

        //未选中的情况
        Cursor falseCursor = database.query("titles", null, "checked = ?", new String[]{Integer.toString(0)}, null, null, null);
        if (falseCursor != null) {
            while (falseCursor.moveToNext()) {
                CategoryTitle title = new CategoryTitle();
                title.setId(falseCursor.getInt(falseCursor.getColumnIndex("id")));
                title.setName(falseCursor.getString(falseCursor.getColumnIndex("name")));
                int checked = falseCursor.getInt(falseCursor.getColumnIndex("checked"));
                if (checked == 1) {
                    title.setChecked(true);
                } else {
                    title.setChecked(false);
                }
                title.setType(falseCursor.getString(falseCursor.getColumnIndex("type")));

                unCheckedTitles.add(title);
            }
            falseCursor.close();

        }

        dc.setCheckedTitles(checkedTitles);
        dc.setUnCheckedTitles(unCheckedTitles);
    }
}
